package com.yun300;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * Hello world!
 *
 */
public class ScreenRecorder
{
    private Robot robot;
    private Rectangle screenRect;
    private String outputDir;
    private int frameRate;

    public ScreenRecorder(String outputDir, int frameRate) {
        try {
            this.robot = new Robot();
        } catch (AWTException e) {
            e.printStackTrace();
        }
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        this.screenRect = new Rectangle(screenSize);
        this.outputDir = outputDir;
        this.frameRate = frameRate;
    }

    public void startRecording() {
        long startTime = System.currentTimeMillis();
        int frameCount = 0;
        while (true) {
            BufferedImage image = robot.createScreenCapture(screenRect);
            File outputFile = new File(outputDir, frameCount + ".png");
            try {
                ImageIO.write(image, "png", outputFile);
                frameCount++;

                long elapsedTime = System.currentTimeMillis() - startTime;
                long targetTime = frameCount * 1000 / frameRate;
                if (elapsedTime < targetTime) {
                    try {
                        Thread.sleep(targetTime - elapsedTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        ScreenRecorder recorder = new ScreenRecorder("C:\\Users\\zhoutanxin\\Desktop\\output", 24);
        recorder.startRecording();
    }

}
